package com.wang;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * session 共享
 */
@RestController
@RequestMapping("/sessions")
@Slf4j
public class SessionsController {

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/set")
    public Map<String, Object> setSession(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        request.getSession().setAttribute("request Url", request.getRequestURL());
        map.put("request Url", request.getRequestURL());
        return map;
    }

    @GetMapping(value = "/list")
    public Object sessions (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", request.getSession().getId());
        map.put("message", request.getSession().getAttribute("request Url"));
        return map;
    }

    @GetMapping("set-value-1")
    public void set() {
        for (int i = 0; i < 150; i++) {
            new Thread(() -> {
                RedisUtil redis = SpringContextUtil.getBean(RedisUtil.class);

                log.info("============= B-{} ====== {}", Thread.currentThread().getName(),redis.get("test_key", 4).toString());
            }, "B" + i).start();

            new Thread(() -> {

                RedisUtil redis = SpringContextUtil.getBean(RedisUtil.class);
                log.info("============= A-{} ====== {}",Thread.currentThread().getName() ,redis.get("test_key", 3).toString());
            }, "A" + i).start();
        }

//        redisUtil.set("test_key","test_value",4);
    }

    @GetMapping("set-value-2")
    public void set2() {
        redisUtil.set("test_key","test_value",3);
    }

    @GetMapping("get-value")
    public String getValue() {

        return (String) redisUtil.get("test_key");
    }

    @GetMapping("/get")
    public ResponseJson get() {
        ResponseJson ok = ResponseJson.ok();

        return ok;
    }

    public static void main(String[] args) {
        ResponseJson chenggong = ResponseJson.builder().msg("chenggong").build();
        System.out.println(chenggong);

        ResponseJson ok = ResponseJson.ok();

        System.out.println(JSON.toJSONString(ok));
    }
}
